package GUI;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JList;
import ControlLayer.ProductCtr;
import ModelLayer.Product;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;

public class ProductList extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7317191210746659083L;
	private JPanel contentPane;
	private JList lstProducts;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ProductList frame = new ProductList();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ProductList() {
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 641, 431);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(null);
		setContentPane(contentPane);
		
		JButton btnGetall = new JButton("getall");
		btnGetall.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateProductList();
			}
		});
		btnGetall.setBounds(526, 359, 97, 25);
		contentPane.add(btnGetall);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(0, 13, 623, 345);
		contentPane.add(scrollPane);
		
		lstProducts = new JList();
		scrollPane.setViewportView(lstProducts);
		
		JButton btnShowProduct = new JButton("show product");
		btnShowProduct.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				showSelectedProduct();
			}
		});
		btnShowProduct.setBounds(429, 359, 97, 25);
		contentPane.add(btnShowProduct);
	}
	private void updateProductList()
	{
		ArrayList<Product> list = new ProductCtr().findAllProduct();
		DefaultListModel<Product> dlist = new DefaultListModel<>();
		for(Product prodoct: list)
			dlist.addElement(prodoct);
		lstProducts.setModel(dlist);
	}
	
	private void showSelectedProduct()
	{
		Object object = lstProducts.getSelectedValue();
		Product p = (Product) object;
		JOptionPane.showMessageDialog(this, p);
	}
	
}
